<template>
<div class="container">
  <el-col v-if="showAdd||showSearch||showMultiDel||$slots.toolbar||$slots.toolbar2||$slots.toolbar3||$slots.toolbar4" :span="24" class="toolbar">
    <slot name="toolbar" />
<!--    <el-button v-if="showAdd" type="primary" icon="el-icon-edit" @click="add">{{addBtn}}</el-button>-->
    <slot name="toolbar2" />
    <el-button v-if="showSearch" type="success" icon="el-icon-search" plain @click="searchVisible=true">{{searchBtn}}</el-button>
    <slot name="toolbar3" />
    <el-button v-if="showMultiDel" type="danger" icon="el-icon-delete" plain @click="delMulti" :disabled="select.length===0">{{multiDelBtn}}</el-button>
    <slot name="toolbar4" />
    <el-button type="primary" icon="el-icon-download" @click="exportExcel" size="medium ">导出数据</el-button>
  </el-col>
  <el-table class="table" id="out-table" :data="data" v-loading="loading" stripe highlight-current-row @row-click="rowClick" @selection-change="sel=>{this.select = sel}">
    <el-table-column v-if="showMultiDel||showCheckBox" type="selection" fixed="left" />
    <el-table-column
      prop="gid"
      label="id"
      width="80"
      sortable>
    </el-table-column>
    <el-table-column
      prop="gname"
      label="商品名"
      sortable>
    </el-table-column>
    <el-table-column
      prop="gcName"
      label="种类名">
    </el-table-column>
    <el-table-column
      prop="introduction"
      label="介绍">
    </el-table-column>
    <el-table-column
      prop="scount"
      label="销量"
      width="90">
    </el-table-column>
    <el-table-column
      prop="sprice"
      label="售价"
      width="90">
    </el-table-column>
    <el-table-column
      prop="gamount"
      label="库存"
      width="90">
    </el-table-column>
    <el-table-column
      prop="pubTime"
      label="日期">
    </el-table-column>
    <el-table-column v-if="showEdit||showDel||$scopedSlots.opBtn||$scopedSlots.opBtn2||$scopedSlots.opBtn3" :label="opBtn" fixed="right" :min-width="opBtnWidth+'px'">
      <template slot-scope="scope">
        <slot name="opBtn" :row="scope.row" />
        <el-button v-if="showEdit" size="small" type="primary" plain @click="edit(scope.row)">{{editBtn}}</el-button>
        <slot name="opBtn2" :row="scope.row" />
        <el-button v-if="showDel" size="small" type="danger" plain @click="del(scope.row)">{{delBtn}}</el-button>
        <slot name="opBtn3" :row="scope.row" />
      </template>
    </el-table-column>
  </el-table>
  <el-pagination v-if="showPage" class="pagebar" background layout="sizes, prev, pager, next, jumper, ->, total" :current-page="page" :page-size="size" :total="total" @size-change="sizeChange" @current-change="currentChange">
  </el-pagination>
  <el-dialog append-to-body v-if="showAdd||showEdit" :title="editTitle" :width="dlgWidth" :visible="editVisible" @close="close" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :label-position="editLabelPosition" :style="{margin:editMargin}" :model="editModel" :label-width="labelWidth+'px'" label-suffix="：" status-icon  ref="editForm">
       <el-form-item label="id">
         <el-input v-model="editModel.gid" disabled/>
       </el-form-item>
      <el-form-item label="名字" >
        <el-input v-model="editModel.gname"/>
      </el-form-item>
      <el-form-item label="种类" >
      <el-input v-model="editModel.gcName" />
    </el-form-item>
      <el-form-item label="介绍" >
        <el-input v-model="editModel.introduction" />
      </el-form-item>
      <el-form-item label="折扣" >
        <el-input v-model="editModel.discount" />
      </el-form-item>
      <el-form-item label="销量" >
        <el-input v-model="editModel.scount" />
      </el-form-item>
      <el-form-item label="售价" >
        <el-input v-model="editModel.sprice" />
      </el-form-item>
      <el-form-item label="库存" >
        <el-input v-model="editModel.gamount" />
      </el-form-item>
      <el-form-item label="时间" >
          <el-date-picker
            v-model="editModel.pubTime"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button icon="el-icon-circle-close-outline" @click="close">{{cancelBtn}}</el-button>
      <el-button icon="el-icon-check" type="primary" @click="submit" :loading="editLoading">{{submitBtn}}</el-button>
    </template>
  </el-dialog>
  <el-dialog append-to-body v-if="showSearch" :title="searchTitle" :width="searchDlgWidth" :visible="searchVisible" @close="searchVisible= false">
    <el-form :label-position="searchLabelPosition" :style="{margin:searchMargin}" :model="searchModel" :label-width="searchLabelWidth+'px'" label-suffix="：">
      <slot name="searchCols" :searchModel="searchModel" >
        <el-form-item label="商品名">
          <el-input v-model="searchModel.gname"></el-input>
        </el-form-item>
      </slot>
    </el-form>
    <template slot="footer">
      <el-button @click="refresh" :loading="loading" icon="el-icon-refresh">{{restoreBtn}}</el-button>
      <el-button type="primary" @click="search" :loading="loading" icon="el-icon-search">{{searchBtn}}</el-button>
    </template>
  </el-dialog>
</div>
</template>

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
import { Message} from 'element-ui'
import * as good from 'src/api/good'
  export default {
    props: {
      idKey: {
        type: String,
        default: "id"
      },
      showMultiDel: {
        type: Boolean,
        default: true
      },
      showCheckBox: {
        type: Boolean,
        default: true
      },
      showDel: {
        type: Boolean,
        default: true
      },
      showEdit: {
        type: Boolean,
        default: true
      },
      showAdd: {
        type: Boolean,
        default: true
      },
      showSearch: {
        type: Boolean,
        default: true
      },
      showPage: {
        type: Boolean,
        default: true
      },
      editDefault: {
        type: Object
      },
      editLabelPosition: {
        type: String,
        default: "right"
      },
      searchLabelPosition: {
        type: String,
        default: "right"
      },
      editMargin: {
        type: String,
        default: "0 30px 0 20px"
      },
      searchMargin: {
        type: String,
        default: "0 30px 0 20px"
      },
      searchLabelWidth: {
        type: Number,
        default: 100
      },
      searchDefault: {
        type: Object
      },
      labelWidth: {
        type: Number,
        default: 100
      },
      dlgWidth: {
        type: String,
        default: "600px"
      },
      searchDlgWidth: {
        type: String,
        default: "500px"
      },
      editBtn: {
        type: String,
        default: "编辑"
      },
      delBtn: {
        type: String,
        default: "删除"
      },
      addBtn: {
        type: String,
        default: "新增"
      },
      searchBtn: {
        type: String,
        default: "筛选"
      },
      multiDelBtn: {
        type: String,
        default: "批量删除"
      },
      restoreBtn: {
        type: String,
        default: "恢复默认"
      },
      cancelBtn: {
        type: String,
        default: "取消"
      },
      submitBtn: {
        type: String,
        default: "提交"
      },
      editTitle: {
        type: String,
        default: "编辑信息"
      },
      searchTitle: {
        type: String,
        default: "筛选数据"
      },
      opBtn: {
        type: String,
        default: "操作"
      },
      opBtnWidth: {
        type: Number,
        default: 200
      },
      delDesc: {
        type: String,
        default: "确认要删除该记录吗?"
      },
      multiDelDesc: {
        type: String,
        default: "确认要删除所选记录吗?"
      },
      editExtendRow: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        page: 1,
        size: 10,
        total: 0,
        data: [],
        select: [],
        loading: false,
        editModel: {
          gid: '',gname:'',gcName:'', introduction: '',discount:0.0, scount: 0, sprice: 0.0, gamount: 0, pubTime: ''
        },
        editVisible: false,
        editLoading: false,
        searchModel: {
          gname: ''
        },
        searchVisible: false,
        editFlag: true,
        editRule: {
          gname: [
            { required: true, message: '请输入名字', trigger: 'blur' },
          ],
          gcName: [
            { required: true, message: '请输入类别', trigger: 'blur' },
          ],
          introduction: [
            { required: true, message: '请输入介绍', trigger: 'blur' },
          ],
          discount: [
            { required: true, message: '请输入折扣', trigger: 'blur' },
          ],
          scount: [
            { required: true, message: '请输入销量', trigger: 'blur' },
          ],
          sprice: [
            { required: true, message: '请输入售价', trigger: 'blur' },
          ],
          gamount: [
            { required: true, message: '请输入库存', trigger: 'blur' },
          ],
          pubTime: [
            { required: true, message: '请输入时间', trigger: 'blur' },
          ],
        }
      };
    },
    methods: {
      getData() {
        this.loading = true;
        const data = {
          currentPage: this.page,
          pageSize: this.size,
        }
        let that = this
        good.getAllGoods(data).then(res => {
          that.data = res.data.data;
          })
        good.countGood().then(res =>{
          this.total = res.data.data
          that.loading = false;
        })
      },
      //定义导出Excel表格事件
      exportExcel() {
        let fix = document.querySelector('.el-table__fixed');
        let wb;
        if(fix){ //判断要导出的节点中是否有fixed的表格，如果有，转换excel时先将该dom移除，然后append回去
          wb = XLSX.utils.table_to_book(document.querySelector('#out-table').removeChild(fix));
          document.querySelector('#out-table').appendChild(fix);
        }else{
          wb = XLSX.utils.table_to_book(document.querySelector('#out-table'));
        }
        let wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
        try {
          FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'sheet1.xlsx')
        } catch (e) {
          if (typeof console !== 'undefined') console.log(e, wbout)
        }
        return wbout
      },
      add() {
        this.editModel = {};
        this.editVisible = true;
        this.$emit("open-edit");
        this.editFlag = false
      },
      edit(row) {
        this.editModel = Object.assign({}, row);
        this.editVisible = true;
        this.$emit("open-edit", row);
        this.editFlag = true

      },
      del(row) {
        this.$confirm(this.delDesc, "警告", {
          type: "warning"
        }).then(() => {
          good.deleteOne(row).then((response) => {
            if (response.data.code === 200) {
              this.$message({
                message: "删除成功",
                type: "success"
              });
            }else {
              this.$message({
                message: "删除失败",
                type: "error"
              });
            }
            this.getData();
          });
        });
      },
      delMulti() {
        const select = this.select
        const that = this
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          good.deleteMulti(select).then(function (response) {
            that.$message({
              type: 'success',
              message: '删除成功!'
            });
            that.getData()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
        this.getData()
      },
      search() {
        this.page = 1;
        this.searchVisible = false;
        this.searchName();
      },
      searchName(){
        const that = this
        this.loading = true;
        good.searchGood(this.searchModel.gname).then(function (response) {
          that.data = response.data.data
          that.total = that.data.length
          that.loading = false;
        })
      },
      refresh() {
        this.page = 1;
        this.searchModel = Object.assign({}, this.searchDefault);
        this.searchVisible = false;
        this.getData();
      },
      submit() {
        this.editLoading = true;
        let ajax;
        if (this.editFlag === false) {
          this.api.add(this.editModel);
        } else {
          console.log(this.editModel)
          good.updateOne(this.editModel).then(function (response) {
            if (response.data.code === 200) {
              Message.success('更新成功')
            } else {
              Message.error('更新失败')
            }
          })
        }
        this.editLoading = false;
        this.editVisible = false;
        this.$refs.editForm.resetFields();
        this.getData();
      },
      close() {
        this.editVisible = false;
        this.$refs.editForm.clearValidate();
      },
      sizeChange(size) {
        this.page = 1;
        this.size = size;
        this.getData();
      },
      currentChange(page) {
        this.page = page;
        this.getData();
      },
      rowClick(row, event, column) {
        this.$emit("row-click", row, event, column);
      }
    },
    watch: {
      editDefault(val) {
        this.editModel = Object.assign(this.editModel, val);
      },
      searchDefault(val) {
        this.searchModel = Object.assign(this.searchModel, val);
        this.$nextTick().then(() => {
          this.getData(1);
        });
      }
    },
    mounted() {
      this.editModel = Object.assign({}, this.editDefault);
      this.searchModel = Object.assign({}, this.searchDefault);
      this.getData();
    }
  };
</script>

<style lang="scss" scoped>
  /*@import "../style/mixin";*/
  .container {
    display: flex;
    flex-direction: column;
    .table {
      margin: 15px 0;
    }
  }
</style>
